#include <iostream>
#include <string.h>

using namespace std;

class String
{
public:
    String(const char *str = NULL);
    String(const String &obj);
    ~String();
    void show(void);
    int size();
    char &operator[](int index);
    const char &operator[](int index) const;

private:
    char *str;
};

char &String::operator[](int index)
{
    return str[index];
}

const char &String::operator[](int index) const
{
    return str[index];
}

int String::size()
{
    if (str)
    {
        return strlen(str);
    }
    else
    {
        return 0;
    }
}

String::String(const char *str)
{
    cout << "String(const char *str)" << endl;
    if (str)
    {
        int len = strlen(str) + 1;
        this->str = new char[len];
        strcpy(this->str, str);
    }
    else
    {
        this->str = NULL;
    }
}

String::String(const String &obj)
{
    cout << "String(const String &obj)" << endl;
    if (obj.str)
    {
        int len = strlen(obj.str) + 1;
        this->str = new char[len];
        strcpy(this->str, obj.str);
    }
    else
    {
        this->str = NULL;
    }
}

String::~String()
{
    cout << "~String()" << endl;
    if (this->str)
    {
        int len = strlen(str) + 1;
        delete[] str;
    }
    str = NULL;
}

void String::show(void)
{
    for (char *p = str; p && (*p != '\0'); p++)
    {
        cout << *p << ", ascii: " << (int)*p << endl;
    }

    return;
}

void func(String &obj)
{
    obj.show();
}

String func_ret(void)
{
    String str("world");
    return str;
}

int main()
{
    String str("hello");

    str[0] = 'w';
    str[1] = 'x';

    for (int i = 0; i < str.size(); i++)
    {
        cout << str[i] << endl;
    }

    return 0;
}